#include "Configuration.h"
#include "GameScene.h"
#include "math.h"
#include <string>
#include <map>
#include <mapbase.h>
#include <win32_utils.h>

GameScene::GameScene(SceneManager& manager,std::unordered_map<std::string, Texture2D>& texture_blocks,Font* font,Hero &hero):sceneManager(manager),texture_blocks(texture_blocks),font(font),hero(hero){
initPictures();

}

void GameScene::init() {
    InitAudioDevice();
    initSounds();
    string mapPath="assets\\maze0.txt";
    initMap(mapPath);
    btn_open.setOnClick([&](){
            // map.save("maz.txt");
            map.search(dfs);
        });
    btn_next.setOnClick([&](){
        WinPressKey(0x80);
        // map.save("maz.txt");
        
    });
    btn_pre.setOnClick([&](){
        // map.save("maz.txt");
    });

    if(!map.path.empty()){
        // hero.x=(float)(3.5*48+5);
        // hero.y=(float)(2*48+5);
        hero.x=(float)map.path[map.currentPath][0].x*48;
        hero.y=(float)map.path[map.currentPath][0].y*48;
    }else{
        hero.x=map.getStartPoint().x*48;
        hero.y=map.getStartPoint().y*48;
    }
    hero.moving=false;
    pauseFlag=false;
    ahead=true;
    initBlocks();
    initMonster();

    fireTimer = clock();
    jumpScareTimer= clock();

    on_fire_count=0;

    moveThreadRunning = true;
    moveThread = std::thread(&GameScene::moveDetectionThread, this);

    detectEventRunning=true;
    detectThread = std::thread(&GameScene::detectEventThread, this);

}

GameScene::~GameScene() {
    if(!IsSoundValid(smile))UnloadSound(smile);
    CloseAudioDevice();

    // 停止线程
    moveThreadRunning = false;
    if (moveThread.joinable()) {
        moveThread.join();
    }
    detectEventRunning = false;
    if (detectThread.joinable()) {
        detectThread.join();
    }
}
//初始化monster
void GameScene::initMonster()
{
    monster.x=3*48;
    monster.y=3*48;
    monster.moving=true;
    monster.setGameScene(this);
    monster.setHero(&hero);
    monster.setMap(&map);
    // monster.startMonsterThread();
}

//初始化TileMap的位置
void GameScene::initMap(string mapPath)
{
    map.initTextures(texture_blocks);

    // map.setFogMode(true);

    map.load(mapPath);
    //获取path路径
    map.search(dfs);
    
}

void GameScene::initPictures()
{
    Image character1 = LoadImage("assets\\jumpScares\\scare01.png");
    Image character2 = LoadImage("assets\\jumpScares\\scare02.png");
    Image const_character1 = LoadImage("assets\\jumpScares\\constant_jump1.png");
    Image const_character2 = LoadImage("assets\\jumpScares\\constant_jump2.png");
    Image const_character3 = LoadImage("assets\\jumpScares\\constant_jump3.png");
    Image const_character4 = LoadImage("assets\\jumpScares\\constant_jump4.png");
    ImageResize(&character1, 2200, 1500);
    ImageResize(&character2, 2200, 1500);
    ImageResize(&const_character1, 2200, 1500);
    ImageResize(&const_character2, 2200, 1500);
    ImageResize(&const_character3, 2200, 1500);
    ImageResize(&const_character4, 2200, 1500);
    Texture2D jumpScare1 = LoadTextureFromImage(character1);
    Texture2D jumpScare2 = LoadTextureFromImage(character2);
    Texture2D const_jumpScare1 = LoadTextureFromImage(const_character1);
    Texture2D const_jumpScare2 = LoadTextureFromImage(const_character2);
    Texture2D const_jumpScare3 = LoadTextureFromImage(const_character3);
    Texture2D const_jumpScare4 = LoadTextureFromImage(const_character4);
    jumpScareTextures.push_back(jumpScare1);
    jumpScareTextures.push_back(jumpScare2);
    jumpScareTextures.push_back(const_jumpScare1);
    jumpScareTextures.push_back(const_jumpScare2);
    jumpScareTextures.push_back(const_jumpScare3);
    jumpScareTextures.push_back(const_jumpScare4);
    cout<<jumpScare1.id<<endl;
    cout<<jumpScare2.id<<endl;
    UnloadImage(character1);
    UnloadImage(character2);
    UnloadImage(const_character1);
    UnloadImage(const_character2);
    UnloadImage(const_character3);
    UnloadImage(const_character4);
}

void GameScene::initSounds()
{
    const string soundPath = "assets\\sounds\\walk.wav";

    std::cout << "   File exists: " << FileExists(soundPath.c_str()) << std::endl;
    smile = LoadSound("assets/sounds/walk.wav");
    SetSoundVolume(smile, 10.0);
}

void GameScene::initBlocks()
{
    // 遍历所有墙壁，分配到对应的网格中
    for (int i = 0; i < map.getMap().size(); i++) {
        for (int j = 0; j < map.getMap()[i].size(); j++) {
            int gridX = (int)(i / Chunk::chunksize);
            int gridY = (int)(j / Chunk::chunksize);

            Rectangle blockRect = { (float)i * 48, (float)j * 48, 48, 48 };//左上角坐标以及宽高
            switch (map.getMap()[i][j])
            {
                case Blocks::wall:
                    heroChunks[{gridX, gridY}].addBlock(blockRect,Blocks::wall);
                    monsterChunks[{gridX, gridY}].addBlock(blockRect,Blocks::wall);
                    break;
                case Blocks::grass:
                    heroChunks[{gridX, gridY}].addBlock(blockRect,Blocks::grass);
                    monsterChunks[{gridX, gridY}].addBlock(blockRect,Blocks::grass);
                    break;
                case Blocks::lava:
                    heroChunks[{gridX, gridY}].addBlock(blockRect,Blocks::lava);
                    monsterChunks[{gridX, gridY}].addBlock(blockRect,Blocks::lava);
                    break;
                case Blocks::floor:
                    heroChunks[{gridX, gridY}].addBlock(blockRect,Blocks::floor);
                    monsterChunks[{gridX, gridY}].addBlock(blockRect,Blocks::floor);
                    break;
            }
        }
    }
}

std::map<int,vector<Rectangle>> GameScene::getBlocks() {
    std::map<int,vector<Rectangle>> blocks;
    // 计算英雄所在的网格坐标
    int heroBlockX = (int)(hero.x / (Chunk::chunksize*48));
    int heroBlockY = (int)(hero.y / (Chunk::chunksize*48));
    for (int dx = -1; dx <= 1; dx++) {
        for (int dy = -1; dy <= 1; dy++) {
            auto key = Coord<int>{heroBlockX + dx, heroBlockY + dy};
                if (heroChunks.find(key) != heroChunks.end()) {
                const auto& chunkMap = heroChunks.at(key).getGridMap();
                for (const auto& [blockType, rects] : chunkMap) {
                    // 将rects追加到对应类型的vector中
                    blocks[blockType].insert(blocks[blockType].end(), 
                                            rects.begin(), rects.end());
                }
            }
        }
    }

    return blocks;
}
std::map<int,vector<Rectangle>> GameScene::getMonsterNearbyBlocks()
{
    std::map<int,vector<Rectangle>> Blocks;
    std::vector<Rectangle> blockWalls;
    std::vector<Rectangle> seedBlocks;
    std::vector<Rectangle> fireBlocks;
    std::vector<Rectangle> floorBlocks;
    // 计算英雄所在的网格坐标
    int monsterBlockX = (int)(monster.x / (Chunk::chunksize*48));
    int monsterBlockY = (int)(monster.y / (Chunk::chunksize*48));
    for (int dx = -1; dx <= 1; dx++) {
        for (int dy = -1; dy <= 1; dy++) {
            auto key = Coord<int>{monsterBlockX + dx, monsterBlockY + dy};
                if (monsterChunks.find(key) != monsterChunks.end()) {
                const auto& chunkMap = monsterChunks.at(key).getGridMap();
                for (const auto& [blockType, rects] : chunkMap) {
                    // 将rects追加到对应类型的vector中
                    Blocks[blockType].insert(Blocks[blockType].end(), 
                                            rects.begin(), rects.end());
                }
            }
        }
    }
    // monster.updateBlocksFromGameScene(Blocks);

    float detectionRadius = 48 * 2; // 检测半径（2倍）
    // 获取Monster一定范围内的墙壁
    std::map<int,vector<Rectangle>> nearbyBlocks;
    Vector2 monsterCenter = { monster.x + 24, monster.y + 24 }; // 英雄中心点

    //pair为map的所有键值对
    for(const auto &pair:Blocks)
    {
        //方块的种类个数
        for(int i=0;i<Blocks[pair.first].size();++i){

            Vector2 wallCenter = { Blocks[pair.first][i].x+24,Blocks[pair.first][i].y+24};
            float distance = sqrt(pow(monsterCenter.x - wallCenter.x, 2) + pow(monsterCenter.y - wallCenter.y, 2));
            if (distance <= detectionRadius) {
                Rectangle blockRect = {Blocks[pair.first][i].x,Blocks[pair.first][i].y, 48, 48 };
                switch (pair.first)
                {
                    case 0:
                        floorBlocks.push_back(blockRect);
                        break;
                    case 1:
                        blockWalls.push_back(blockRect);
                        break;
                    case 2:
                        seedBlocks.push_back(blockRect);
                        break;
                    case 3:
                        fireBlocks.push_back(blockRect);
                    default:
                        break;
                }
                map.visibleBlocks[std::make_pair(Blocks[pair.first][i].x/48,Blocks[pair.first][i].y/48)]=true;
            }else
            {
                if(map.visibleBlocks[std::make_pair(Blocks[pair.first][i].x/48,Blocks[pair.first][i].y/48)]&&map.fogMode)
                    map.visibleBlocks[std::make_pair(Blocks[pair.first][i].x/48,Blocks[pair.first][i].y/48)]=false;
            }
        }
    }
    nearbyBlocks.emplace(0,floorBlocks);
    nearbyBlocks.emplace(1,blockWalls);
    nearbyBlocks.emplace(2,seedBlocks);
    nearbyBlocks.emplace(3,fireBlocks);
    return nearbyBlocks;//正常情况下只有不超过8个
}

std::map<int,vector<Rectangle>> GameScene::getNearbyBlocks()
{
    std::map<int,vector<Rectangle>> Blocks=getBlocks();
    std::vector<Rectangle> blockWalls;
    std::vector<Rectangle> seedBlocks;
    std::vector<Rectangle> fireBlocks;
    std::vector<Rectangle> floorBlocks;

    float detectionRadius = 48 * 2; // 检测半径（2倍）
    // 获取英雄一定范围内的墙壁
    std::map<int,vector<Rectangle>> nearbyBlocks;
    Vector2 heroCenter = { hero.x + 24, hero.y + 24 }; // 英雄中心点

    //pair为map的所有键值对
    for(const auto &pair:Blocks)
    {
        //方块的种类个数
        for(int i=0;i<Blocks[pair.first].size();++i){
            //对应
            Vector2 wallCenter = { Blocks[pair.first][i].x+24,Blocks[pair.first][i].y+24};
            float distance = sqrt(pow(heroCenter.x - wallCenter.x, 2) + pow(heroCenter.y - wallCenter.y, 2));
            if (distance <= detectionRadius) {
                Rectangle blockRect = {Blocks[pair.first][i].x,Blocks[pair.first][i].y, 48, 48 };
                switch (pair.first)
                {
                    case 0: 
                        floorBlocks.push_back(blockRect);
                        break;
                    case 1:
                        blockWalls.push_back(blockRect);
                        break;
                    case 2:
                        seedBlocks.push_back(blockRect);
                        break;
                    case 3:
                        fireBlocks.push_back(blockRect);
                    default:
                        break;
                }
                map.visibleBlocks[std::make_pair(Blocks[pair.first][i].x/48,Blocks[pair.first][i].y/48)]=true;
            }else
            {
                if(map.visibleBlocks[std::make_pair(Blocks[pair.first][i].x/48,Blocks[pair.first][i].y/48)]&&map.fogMode)
                    map.visibleBlocks[std::make_pair(Blocks[pair.first][i].x/48,Blocks[pair.first][i].y/48)]=false;
            }
        }
    }
    nearbyBlocks.emplace(0,floorBlocks);
    nearbyBlocks.emplace(1,blockWalls);
    nearbyBlocks.emplace(2,seedBlocks);
    nearbyBlocks.emplace(3,fireBlocks);
    return nearbyBlocks;//正常情况下只有不超过8个
    // return getBlocks();
}


int GameScene::evaluate_wall_to_hero(Rectangle wall)
{
    if(wall.x>hero.x)//在人右面
        return 1;
    else if(wall.x<hero.x)//在人左面
        return 3;
    else if(wall.y>hero.y)//在人下面
        return 2;
    else //墙在人的上面
        return 0;
}


//特殊地形或者其他事件的碰撞检测
void GameScene::detectEventThread()
{
    while(detectEventRunning){
        std::map<int,vector<Rectangle>> blocks=getNearbyBlocks();
        Rectangle heroRect=hero.getRectangle();
        Rectangle monsterRect=monster.getRectangle();

        bool onGrass=false;
        for(vector<Rectangle>::iterator itr=blocks[2].begin();itr!=blocks[2].end();++itr)
        {
            Rectangle eventRect=*(itr);
            if(getCollision(heroRect,eventRect))
            {
                onGrass=true;
                break;
            }
        }
        run_on_grass=onGrass;


        bool onFire=false;
        for(vector<Rectangle>::iterator itr=blocks[3].begin();itr!=blocks[3].end();++itr)
        {
            Rectangle eventRect=*(itr);
            if(getCollision(heroRect,eventRect))
            {
                onFire=true;
                clock_t now = clock();
                // 每隔5秒才开始计算一次踩火次数
                if(double(now - fireTimer) / CLOCKS_PER_SEC >=5.0f)
                {
                    on_fire_count++;
                    fireTimer = now;
                }
                break;
            }
        }
        run_on_fire=onFire;

        bool inMonster=false;
        if(getCollision(heroRect,monsterRect)){
            inMonster=true;
        }
        run_in_monster=inMonster;

    }
}

void GameScene::moveDetectionThread() {
    while (moveThreadRunning) {
        if(run_on_grass) {
            hero.step = hero.originStep * 0.5f;  // 在草地上速度减半
        } else {
            hero.step = hero.originStep;         // 正常速度
        }
        if(hero.isLive) {
            // 检测按键按下，添加到数组
            if(IsKeyDown(KEY_W) && 
               find(activeDirections.begin(), activeDirections.end(), 0) == activeDirections.end()) {
                activeDirections.push_back(0);
            }
            if(IsKeyDown(KEY_D) && 
               find(activeDirections.begin(), activeDirections.end(), 1) == activeDirections.end()) {
                activeDirections.push_back(1);
            }
            if(IsKeyDown(KEY_S) && 
               find(activeDirections.begin(), activeDirections.end(), 2) == activeDirections.end()) {
                activeDirections.push_back(2);
            }
            if(IsKeyDown(KEY_A) && 
               find(activeDirections.begin(), activeDirections.end(), 3) == activeDirections.end()) {
                activeDirections.push_back(3);
            }
            
            // 检测按键释放，从数组中移除
            if(IsKeyUp(KEY_W)) {
                auto it = find(activeDirections.begin(), activeDirections.end(), 0);
                if (it != activeDirections.end()) {
                    activeDirections.erase(it);
                }
            }
            if(IsKeyUp(KEY_D)) {
                auto it = find(activeDirections.begin(), activeDirections.end(), 1);
                if (it != activeDirections.end()) {
                    activeDirections.erase(it);
                }
            }
            if(IsKeyUp(KEY_S)) {
                auto it = find(activeDirections.begin(), activeDirections.end(), 2);
                if (it != activeDirections.end()) {
                    activeDirections.erase(it);
                }
            }
            if(IsKeyUp(KEY_A)) {
                auto it = find(activeDirections.begin(), activeDirections.end(), 3);
                if (it != activeDirections.end()) {
                    activeDirections.erase(it);
                }
            }
            
            hero.moving = !activeDirections.empty();

            //更新方向，不等待碰撞检测
            if (!activeDirections.empty()) {
                int lastDirection = activeDirections.back();
                hero.direction = lastDirection;  // 方向立即改变
                //获取周围的墙壁
                std::vector<Rectangle> nearWalls= getNearbyBlocks()[1];
                bool collisionFlag;

                // 保存原始位置
                float originalX = hero.x;
                float originalY = hero.y;

                switch (lastDirection) {
                    case 0: hero.run_up(hero.step); break;
                    case 1: hero.run_right(hero.step); break;
                    case 2: hero.run_down(hero.step); break;
                    case 3: hero.run_left(hero.step); break;
                }

                Rectangle heroBox=hero.getRectangle();
                for(int i=0;i<nearWalls.size();i++)
                {
                    collisionFlag=getCollision(heroBox,nearWalls[i]);
                    if(collisionFlag)break;
                }
                // 如果碰撞，恢复位置
                if(collisionFlag) {
                    hero.x = originalX;
                    hero.y = originalY;
                }
            }
        }
        // 休眠控制检测频率
        std::this_thread::sleep_for(std::chrono::milliseconds(7));
    }
}


//获取hero当前的二维数组位置
Vector2 GameScene::getHeroPosition()
{
    Vector2 drawPosition = {hero.x, hero.y};
    return drawPosition;
}

//刷新人物动画帧
void GameScene::refreshHeroCurrentFrames(float deltaTime)
{
    hero.frameTimer += deltaTime;
    if (hero.frameTimer >= hero.frameTime)
    {
        hero.currentFrame = (hero.currentFrame + 1) % 3;
        hero.frameTimer = 0;
    }
}

void GameScene::refreshMonsterCurrentFrames(float deltaTime)
{
    monster.frameTimer += deltaTime;
    if (monster.frameTimer >= monster.frameTime)
    {
        monster.currentFrame = (monster.currentFrame + 1) % 3;
        monster.frameTimer = 0;
    }
}




//两点间移动，附属函数，单独不能实现连续移动
int GameScene::goto_from_to(Vector2 start,Vector2 end)
{   
    
    float distance = sqrt(pow(end.x - start.x, 2) + pow(end.y - start.y, 2));
    
    // 如果已经很接近目标点，认为已经到达
    if (distance < hero.step) {
        return -1; // 表示到达目标
    }
    
    if(start.x < end.x) { // 向右
        hero.moving = true;
        hero.run_right(hero.step);
        hero.direction=1;
        return 1;
    }
    else if(start.x > end.x) { // 向左
        hero.moving = true;
        hero.run_left(hero.step);
        hero.direction=3;
        return 3;
    }
    else if(start.y > end.y) { // 向上
        hero.moving = true;
        hero.run_up(hero.step);
        hero.direction=0;
        return 0;
    }
    else if(start.y < end.y) { // 向下
        hero.moving = true;
        hero.run_down(hero.step);
        hero.direction=2;
        return 2;
    } else {
        return -1; // 已经到达
    }
}

float getDistance(Vector2 start,Vector2 end)
{
    float distance = sqrt(pow(end.x - start.x, 2) + pow(end.y - start.y, 2));
    return distance;
}   

//自动往回走
void GameScene::go_back()
{
    Vector2 start = {hero.x, hero.y};
    Vector2 end = {
        (float)map.path[map.currentPath][nodeCount].x * 48,
        (float)map.path[map.currentPath][nodeCount].y * 48
    };

    float distance = getDistance(start,end);
    if (distance < hero.step * 1.5f) {
        // 对齐目标
        hero.x = end.x;
        hero.y = end.y;
        decreaseNode();
        return;
    }
    goto_from_to(start, end);

    Vector2 newPos = {hero.x, hero.y};
    float newDistance = getDistance(newPos,end);

    //放宽限制，即差不多就可以判定为到达
    float tolerance = hero.step * 2.0f;
    if (newDistance < tolerance) {
        hero.x = end.x;
        hero.y = end.y;
        decreaseNode();
    }

}

//当前节点加一，附属函数
void GameScene::increaseNode()
{
    if(nodeCount<map.path[map.currentPath].size()-1)
        nodeCount+=1;
}

//当前节点减一
void GameScene::decreaseNode()
{
    if(nodeCount>0)
        nodeCount-=1;
}

//自动向前走
void GameScene::go_ahead()
{

    if (map.currentPath >= map.path.size() || 
        map.path[map.currentPath].empty() ||
        nodeCount + 1 >= map.path[map.currentPath].size()) {
        hero.moving = false;
        return;
    }

    Vector2 start = {hero.x, hero.y};
    Vector2 end = {
        (float)map.path[map.currentPath][nodeCount + 1].x * 48, 
        (float)map.path[map.currentPath][nodeCount + 1].y * 48
    };
    
    float distance = sqrt(pow(end.x - start.x, 2) + pow(end.y - start.y, 2));
    if (distance < hero.step * 1.5f) {
        // 对齐目标
        hero.x = end.x;
        hero.y = end.y;
        increaseNode();
        return;
    }
    goto_from_to(start, end);

    Vector2 newPos = {hero.x, hero.y};
    float newDistance = sqrt(pow(end.x - newPos.x, 2) + pow(end.y - newPos.y, 2));

    //放宽限制，即差不多就可以判定为到达
    float tolerance = hero.step * 2.0f;
    if (newDistance < tolerance) {
        hero.x = end.x;
        hero.y = end.y;
        increaseNode();
    }

}

//测试部分按键功能
void GameScene::test()
{
    if(IsKeyDown(KEY_R))
        if (!map.path.empty() && map.currentPath < map.path.size() && 
                !map.path[map.currentPath].empty()) {
                hero.x = (float)map.path[map.currentPath][0].x * 48;
                hero.y = (float)map.path[map.currentPath][0].y * 48;
                nodeCount = 0; // 重置节点计数
                on_fire_count=0;
                badEnd=false;
            }
    if(IsKeyPressed(KEY_P))
    {
        if (!map.path.empty() && map.currentPath < map.path.size() && 
                !map.path[map.currentPath].empty()){

                    if(isEnd()){
                        hero.moving=!hero.moving;
                    }
                    pauseFlag=!pauseFlag;
            }
    }
    //转向
    if(IsKeyPressed(KEY_L))
    {
        ahead=!ahead;
    }
}

void drawJumpScare(Texture2D tex)
{
   // 获取屏幕尺寸
    int screenWidth = GetScreenWidth();
    int screenHeight = GetScreenHeight();
    
    // DrawRectangle(0, 0, screenWidth, screenHeight, RED);
    // 全屏绘制
    DrawTexturePro(tex, 
                  Rectangle{0, 0, (float)tex.width, (float)tex.height},  // 源矩形（整个纹理）
                  Rectangle{0, 0, (float)screenWidth, (float)screenHeight}, // 目标矩形（全屏）
                  Vector2{0, 0},  // 原点
                  0.0f,             // 旋转
                  WHITE);           // 颜色
    // DrawTexture(tex,0,0,WHITE);
    // DrawRectangle(0, 0, GetScreenWidth(), GetScreenHeight(), RED);
}

//是否到达终点
bool GameScene::isEnd()
{
    if(!map.path.empty()){
        if((nodeCount+1)>=(int)map.path[map.currentPath].size()-1||getEndPlace()||badEnd)
            return true;
        else
            return false;
    }else
        return false;
}

bool GameScene::getEndPlace()
{
    Coord<int> endPlace=map.getEndPoint();
    Rectangle endPlaceRec={endPlace.x*48,endPlace.y*48,48,48};
    Rectangle heroRec=hero.getRectangle();
    if(getCollision(heroRec,endPlaceRec))
        return true;
    else
        return false;
}


void drawBlockLine(std::map<int,vector<Rectangle>> nearBlocks,int i,Color color)
{
    for(std::vector<Rectangle>::iterator itr=nearBlocks[i].begin();itr!=nearBlocks[i].end();++itr)
    {
        Rectangle block=*(itr);
        DrawLineEx({block.x,block.y},{block.x+block.width,block.y},2,color);//上边
        DrawLineEx({block.x,block.y},{block.x,block.y+block.height},2,color);//左边
        DrawLineEx({block.x+block.width,block.y},{block.x+block.width,block.y+block.height},2,color);//右边
        DrawLineEx({block.x,block.y+block.height},{block.x+block.width,block.y+block.height},2,color);//下边
    }
}

void drawHeroLine(Hero hero)
{
    Rectangle heroRec=hero.getRectangle();
    DrawLineEx({heroRec.x,heroRec.y},{heroRec.x+heroRec.width,heroRec.y},1,GREEN);//上边
    DrawLineEx({heroRec.x,heroRec.y},{heroRec.x,heroRec.y+heroRec.height},1,GREEN);//左边
    DrawLineEx({heroRec.x+heroRec.width,heroRec.y},{heroRec.x+heroRec.width,heroRec.y+heroRec.height},1,GREEN);//右边
    DrawLineEx({heroRec.x,heroRec.y+heroRec.height},{heroRec.x+heroRec.width,heroRec.y+heroRec.height},1,GREEN);//下边
    
}

void GameScene::handleMonster()
{
    monster.updateFromGameScene(this);
    monster.handleChangeDirection();
    monster.handleMovement();
}

void GameScene::updateShowInfo(double gameSceneTimeInterval)
{
    //更新信息
    heroPositon="hero("+std::to_string(hero.x)+","+std::to_string(hero.y)+")";
    monsterPositon="monster("+std::to_string(monster.x)+","+std::to_string(monster.y)+")";
    this->gameSceneTimeInterval=gameSceneTimeInterval;
}
void GameScene::updateShowInfo()
{
    //更新信息
    heroPositon="hero("+std::to_string(hero.x)+","+std::to_string(hero.y)+")";
    monsterPositon="monster("+std::to_string(monster.x)+","+std::to_string(monster.y)+")";
}
bool timeRangeIn(double timeInterval,double start,double end)
{
    return timeInterval>=start&&timeInterval<=end;
}

void GameScene::handleDrawJumpScare()
{ 
    clock_t scareNow = clock();
    // if(!hasPlayed){  
    //     PlaySound(smile);
    //     hasPlayed=true;
    // }
    // 每隔5秒更新一次
    double timeInterval = double(scareNow - jumpScareTimer) / CLOCKS_PER_SEC;
    updateShowInfo(timeInterval);
    if(timeInterval >=5.0f&&run_in_monster)
    {
        jumpScareTimer = scareNow;
        canDrawJumpScare = true;
    }else if(timeInterval >=5.0f&&run_on_fire)
    {
        jumpScareTimer = scareNow;
        canDrawJumpScareForLava = true;
    }
    timeInterval = double(scareNow - jumpScareTimer) / CLOCKS_PER_SEC;
    if(canDrawJumpScareForLava){
        if(on_fire_count==1&&run_on_fire)
        {
            if(timeRangeIn(timeInterval,0.0f,0.2f))
                drawJumpScare(jumpScareTextures[0]);
            else canDrawJumpScareForLava = false;
        }else if(on_fire_count>=2&&run_on_fire)
        {
            if(timeRangeIn(timeInterval,0.0f,0.7f))
            {
                drawJumpScare(jumpScareTextures[2]);
            }else if(timeRangeIn(timeInterval,0.7f,0.75f))
            {
                drawJumpScare(jumpScareTextures[3]);
            }else if(timeRangeIn(timeInterval,0.75f,0.8f))
            {
                drawJumpScare(jumpScareTextures[4]);
            }else if(timeRangeIn(timeInterval,0.8f,1.2f))
            {
                drawJumpScare(jumpScareTextures[5]);
                badEnd=true;
            }else
            {
                canDrawJumpScareForLava = false;
            }
        }
    }
    
    if(canDrawJumpScare){
        if(timeRangeIn(timeInterval,0.0f,0.2f))
        {
            drawJumpScare(jumpScareTextures[1]);
        }else if(timeRangeIn(timeInterval,0.2f,0.4f))
        {
            drawJumpScare(jumpScareTextures[0]);
        }else if(timeRangeIn(timeInterval,0.4f,1.27f))
        {
            drawJumpScare(jumpScareTextures[2]);
        }else if(timeRangeIn(timeInterval,1.27f,1.32f))
        {
            drawJumpScare(jumpScareTextures[3]);
        }else if(timeRangeIn(timeInterval,1.32f,1.37f))
        {
            drawJumpScare(jumpScareTextures[4]);
        }else if(timeRangeIn(timeInterval,1.37f,1.60f))
        {
            drawJumpScare(jumpScareTextures[5]);
        }else
        {
            canDrawJumpScare = false;
        }
    }
}


void GameScene::render(float deltaTime)
{
    //测试一些功能按键
    test();

    if(!isEnd()){
        handleMonster();
    }

    if(!pauseFlag){
        if (!map.path.empty() && map.currentPath < map.path.size() && nodeCount + 1 < map.path[map.currentPath].size()) 
            {
                if(ahead){
                    go_ahead();
                }else
                {
                    go_back();
                }
            } 
    }   
    // 使人物自动走到终点后停止重绘动画
    hero.moving=!isEnd();

    // 更新动画和方向
    hero.changeDirection(hero.direction);
    if(hero.moving && !pauseFlag) {
        refreshHeroCurrentFrames(deltaTime);
    }
    if(monster.moving&&!isEnd()) {
        refreshMonsterCurrentFrames(deltaTime);
    }
    
    ClearBackground(WHITE);
    map.render();

    std::map<int,vector<Rectangle>> nearBlocks= getNearbyBlocks();
    Vector2 drawHeroPosition = hero.getPosition();
    Vector2 drawMonsterPosition = monster.getPosition();


    updateShowInfo();
    BeginMode2D(map.camera);
    //绘制人物
    DrawTextureRec(hero.chara_texture, hero.actionFrames[hero.currentFrame], drawHeroPosition, WHITE);
    //绘制monster
    DrawTextureRec(monster.chara_texture, monster.actionFrames[monster.currentFrame], drawMonsterPosition, WHITE);
    //绘制墙壁边界
    drawBlockLine(nearBlocks,1,RED);
    //绘制草方块边界
    drawBlockLine(nearBlocks,2,YELLOW);
    //绘制火方块边界
    drawBlockLine(nearBlocks,3,PURPLE);
    //绘制人物碰撞箱
    drawHeroLine(hero);
    
    //显示调试信息
    DrawText(monster.existHeroInCR().first?"chasing":"stop",500,100,20,BLACK);
    DrawText(std::to_string(on_fire_count).c_str(),500,150,20,BLACK);
    DrawText(heroPositon.c_str(),500,200,20,BLACK);
    DrawText(monsterPositon.c_str(),500,250,20,BLACK);
    for(int i=0;i<monster.chasePath.size();i++){
        Vector2 pos={monster.chasePath[i].x*48+24,monster.chasePath[i].y*48+24};
        DrawCircleV(pos,5,BLUE);
    }
    DrawText(canDrawJumpScare?"true":"false",550,50,20,BLACK);
    DrawText(std::to_string(monster.levelTime).c_str(),600,100,20,BLACK);
    DrawText(std::to_string(gameSceneTimeInterval).c_str(),600,400,20,BLACK);

    if(isEnd()&&!badEnd)
    {
        DrawText("You Win!",45,60,100,RED);
    }else if(badEnd)
    {
        DrawText("You Lose!",40,60,100,RED);
    }
    EndMode2D(); 
    
    btn_next.render();
    btn_open.render();
    btn_pre.render();
    
    handleDrawJumpScare();
}